<?php
/**
 * Created by PhpStorm.
 * User: winleung
 * Date: 2019-10-22
 * Time: 23:12
 */

namespace app\api\service;

use app\api\model\PharmacyModel;
use app\api\model\PharmacyOrderModel;
use app\api\model\Pharmacy;
use dada\api\AddShopApi;
use dada\config\Config;
use dada\client\DadaRequestClient;
use ShopAddModel;
use think\Db;
use think\Log;

/**
 * Class PharmacyService
 * @package app\service
 */
class PharmacyService
{
    private $model;
    private $pharmacyModel;
    private $pharmacyOrderModel;

    public function __construct()
    {
        $this->pharmacyOrderModel = new PharmacyOrderModel();
        $this->pharmacyModel = new PharmacyModel();
        $this->model = new Pharmacy();
    }


    public function registerPharmacyAccount($params)
    {
        $result = $this->model->createPharmacyAccount($params);
        if (!$result) {
            throwBusinessException("注册失败");
        }
        return $result;
    }

    /**
     * 更新审核状态，并上传达达
     * @param $params
     */
    public function updatePharmacyStatus($params)
    {
        // 判断是否通过审核
        if ($params['check_status'] == PHARMACY_STATUS_PASS) {
            // 同步到达达
            $pharmacyInfo = $this->syncToDada($params['pharmacy_id']);
            // 同步到redis
            $this->syncToRedis($pharmacyInfo);
        }

        $result = $this->pharmacyModel->updateCheckStatus($params['pharmacy_id'], $params['check_status']);

        if (!$result) {
            throwBusinessException("更新审核状态失败");
        }

        return $result;
    }

    public function getPharmacyInfo($params)
    {
        $pharmacyInfo = $this->model->getPharmacyInfoById(['pharmacy_id' => $params]);

        if (!isset($pharmacyInfo)) {
            throwBusinessException("店铺不存在");
        }

        return $pharmacyInfo;
    }

    public function syncToRedis($pharmacyInfo)
    {
        $redis = new \Redis();

        $rb = $redis->connect('127.0.0.1', 6379);
        $result = null;
        if ($rb) {
            $result = $redis->rawCommand('geoadd', PHARMACY_LOCATION, $pharmacyInfo->longitude, $pharmacyInfo->latitude, $pharmacyInfo->id);

            if (!$result) {
                throwBusinessException("建立地理坐标失败");
            }
        } else {
            throwBusinessException("连接redis失败");
        }

        return $result;
    }

    /**
     * 同步到达达
     */
    private function syncToDada($pharmacyId)
    {
        $config = Config::newConfig();

        $pharmacyInfo = $this->model->getPharmacyInfoById(['pharmacy_id' => $pharmacyId]);

        if (!isset($pharmacyInfo)) {
            throwBusinessException("店铺不存在");
        }

        $shopModel = new ShopAddModel();
        // 门店名称
        $shopModel->setStationName($pharmacyInfo->pharmacy_name);
        /**
         * 业务类型(食品小吃-1,饮料-2,鲜花-3,文印票务-8,便利店-9,水果生鲜-13,同城电商-19, 医药-20,蛋糕-21,酒品-24,小商品市场-25,服装-26,汽修零配-27,数码-28,小龙虾-29, 其他-5)
         */
        $shopModel->setBusiness(20);
        // 城市名称(如,上海)
        $shopModel->setCityName($pharmacyInfo->city_name);
        // 区域名称(如,浦东新区)
        $shopModel->setAreaName($pharmacyInfo->area_name);
        // 门店地址
        $shopModel->setStationAddress($pharmacyInfo->address);
        // 门店纬度
        $shopModel->setLat($pharmacyInfo->latitude);
        // 门店经度
        $shopModel->setLng($pharmacyInfo->longitude);
        // 联系人姓名
        $shopModel->setContactName($pharmacyInfo->contact_name);
        // 联系人电话
        $shopModel->setPhone($pharmacyInfo->pharmacy_mobile_phone);
        // 门店编码,可自定义,但必须唯一;若不填写,则系统自动生成
        $shopModel->setOriginShopId($pharmacyInfo->id);

        $shopAddApi = new AddShopApi(json_encode($shopModel));

        $dada_client = new DadaRequestClient($config, $shopAddApi);

        $resp = $dada_client->makeRequest();
        if ($resp['code'] !== 0) {
            throwBusinessException("同步达达失败");
        };
        return $pharmacyInfo;
    }


    /**
     * 药店登录
     * @param $mobilePhone
     * @param $password
     * @return mixed
     * @throws \Exception
     */
    public function login($mobilePhone, $password, $code = '')
    {

        if (empty($mobilePhone) || empty($password)) {
            throw new \Exception('登录的手机号码或者密码不能为空!');
        }

        $pharmacy = $this->pharmacyModel->fetchPharmacy($mobilePhone, $password);

        if (empty($pharmacy)) {
            throw new \Exception('手机号码或者密码错误!');
        }

        if(!empty($code)){
            $appId = \config('wechat.appid');

            $wechatInfo = new WechatInfoService();

            $openid = $wechatInfo->getWechatOpenId($appId, $code);

            if($openid){
                $this->pharmacyModel->updatePharmacyAccountOpneid($pharmacy['id'], $openid);
            }

        }

        unset($pharmacy['password']);
        return $pharmacy;

    }

    /**
     * 通过openid获取药店用户信息
     * @param $openId
     */
    public function getUserInfoByOpenid($openId){

        $data = $this->pharmacyModel->getPharmacyInfoByOpenId($openId);

        if($data === false){
            return [];
        }

        unset($data['password']);

        return $data;

    }

    /**
     * 提交审核资料
     * @param $userId
     * @param $longitude
     * @param $latitude
     * @param $address
     * @param $businessLicenseImg
     * @param $licensedPharmacistLicenseImg
     * @param $drugTradingLicenseImg
     * @return bool
     * @throws \think\db\exception\DbException
     */
    public function submitCheckInfo($userId, $longitude, $latitude, $address, $businessLicenseImg, $licensedPharmacistLicenseImg, $drugTradingLicenseImg)
    {

        if (empty($userId) || empty($longitude) || empty($latitude) || empty($address) || empty($businessLicenseImg) || empty($licensedPharmacistLicenseImg) || empty($drugTradingLicenseImg)) {
            throw new \Exception('审核资料不能有空!');
        }

        $result = $this->pharmacyModel->addCheckPharmacyInfo($userId, $longitude, $latitude, $address, $businessLicenseImg, $licensedPharmacistLicenseImg, $drugTradingLicenseImg);

        return $result;
    }


    /**
     * 药店获取待处理的订单
     * @param $pharmacyId
     */
    public function fetchToAcceptOrder($pharmacyId)
    {

        $result = $this->pharmacyOrderModel->fetchAcceptPharmacyOrderByStatus($pharmacyId, 1);

        return $result;
    }


    /**
     * 药店获取待处理的订单
     * @param $pharmacyId
     */
    public function fetchHasDoneOrder($pharmacyId)
    {

        $result = $this->pharmacyOrderModel->fetchAcceptPharmacyOrderByStatus($pharmacyId, 888);

        return $result;
    }

    /**
     * 获取药店派发的药店
     * @param $pharmacyId
     * @return int|string
     */
    public function fetchDistributeOrderPharmacyCount($pharmacyId)
    {

        $count = $this->pharmacyModel->fetchPatchOrderCount($pharmacyId);

        return $count;
    }

    /**
     * 药店接单拣货
     * @param $pharmacyId
     * @param $orderId
     * @return bool
     */
    public function pickingOrder($pharmacyId, $orderId)
    {

        $result = $this->pharmacyOrderModel->updatePharmacyOrderStatus($pharmacyId, $orderId, ['status'=>2]);

        return $result;

    }


    /**
     * 药店接单拣货
     * @param $pharmacyId
     * @param $orderId
     * @return bool
     */
    public function donePickingOrder($pharmacyId, $orderId, $imageUrl)
    {

        $result = $this->pharmacyOrderModel->updatePharmacyOrderStatus($pharmacyId, $orderId, ['status'=>3, 'image_url'=>$imageUrl]);


        return $result;

    }

    /**
     * 根据药店的注册的手机号码获取openid
     * @param $mobile
     * @return bool
     */
    public function getOpenidByMobile($mobile){
        $sql = "SELEct b.openid from jn_user a inner join jn_wx_client b on a.id = b.uid where username = ?";
        $result = Db::query($sql, [$mobile]);
        if(empty($result)){
            return false;
        }else{
            return $result[0]['openid'];
        }
    }

    public function getPharmacyOrderToPickings($pharmacyId){

        $data = $this->pharmacyOrderModel->fetchAcceptPharmacyOrderByStatus($pharmacyId, 2);

        return $data;
    }

    /**
     * 获取已审核的药店列表
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getPharmacyInfoList(){

        $data = $this->pharmacyModel->getPharmacyInfoList();

        return $data;
    }


}